<?php
class UsuariosAmigo extends AppModel {

    var $name = 'UsuariosAmigo';                
	var $recursive = -1;
	var $actsAs = array('Containable');
	
    var $belongsTo = array(
        'Amigo' => array(
            'className'    => 'Amigo',
			'joinTable' => 'usuarios',
			'foreignKey' => 'amigo_id',
        ),
        'Usuario' => array(
            'className'    => 'Usuario',
			'joinTable' => 'usuarios',
            'foreignKey' => 'usuario_id',
        )
    ); 

	const ACCEPTED_FRIENDSHIP = 'A';
	const PENDING_ACCEPT = 'P';
	const REJECTED = 'N';

	public $_findMethods = array('amigos' => true);

	public function _findAmigos($state, $query, $results = array()) {
		if ($state == 'before') {
			if (!empty($query['usuario'])) {
					$defaultConditions = array(
						'OR' => array(
							'usuario_id' => $query['usuario'],
							'amigo_id' => $query['usuario']
						)
					);
					$query['conditions'][] = $defaultConditions;
			}
			$query['contain'] = array('Amigo', 'Usuario');
			$query['conditions']['UsuariosAmigo.status'] = self::ACCEPTED_FRIENDSHIP;
			if (!empty($query['operation']) && $query['operation'] === 'count') {
				unset($query['limit']);
				$query = $this->_findCount('before', $query, $results);
			}

			return $query;
		}

		if (isset($query['operation']) && $query['operation'] == 'count') {
			return $this->_findCount('after', $query, $results);
		}

		foreach ($results as &$result) {
			if ($result['Usuario']['id'] != $query['usuario']) {
				$result['Amigo'] = $result['Usuario'];
			}
			unset($result['Usuario']);
		}
		return $results;
	}
	
	public function paginateCount($conditions = array(), $recursive = 0, $extra = array()) {
		$parameters = compact('conditions');
		if ($recursive != $this->recursive) {
			$parameters['recursive'] = $recursive;
		}
		if (isset($extra['type']) && isset($this->_findMethods[$extra['type']])) {
			$extra['operation'] = 'count';
			return $this->find($extra['type'], array_merge($parameters, $extra));
		} else {
			return $this->find('count', array_merge($parameters, $extra));
		}
	}
}
?>